/**
 * 试算模态框
 * 2022-11-09
 */
import React from 'react';
import { connect } from 'dva';
import { ModalC, TableC } from '../../../../comps';
import style from './index.less';
import moment from 'moment';
import { message } from 'antd';
import keyWordConfig from '../../../PortfolioMnt/BookkeepingMnt/config';
import OrderC from '../../../../comps/business/orderC';

class theTrialC extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [], // 表格头
      dataSource: [], // 表格数据
      pageInfo: {
        // 页码信息
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页数量
        total: 0, // 总数
      },
      visibleStep: false, // 下达loading框
      orderParams: {}, // 下达时的入参
    };
  }

  componentDidMount() {
    this.getTableData();
  }

  // 获取表格数据
  getTableData = () => {
    const { dispatch, productCode } = this.props;
    const { pageInfo } = this.state;
    dispatch({
      type: 'portfolioTrialM/getList',
      payload: {
        portfolioCodes: [productCode],
        templateId: 'BASE',
        type: ['7', '12'],
        currentPage: pageInfo.currentPage,
        numInPage: pageInfo.pageSize,
      },
      callback: (res) => {
        if (res) {
          const newColumns = res.columns.filter((i) => i.workStation);
          this.setState({
            columns: newColumns, // 表格头
            dataSource: res.dataSource.filter((i) => i.isTrialferBook !== 'Y'), // 表格数据
            pageInfo: res.pageInfo, // 页码信息
          });
        } else {
          this.setState({
            dataSource: [], // 表格数据
          });
        }
      },
    });
  };

  // 表格页码响应
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        pageInfo: {
          ...this.state.pageInfo,
          currentPage: current,
          pageSize,
        },
      },
      () => this.getTableData(),
    );
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: 110,
        // fixed: 'right',
        operates: [
          // isTrial=Y代表试算未生效
          // 如果某条数据没有试算过，就展示试算按钮，
          // 如果试算过但未转簿记，就展示撤销和转簿记按钮，
          // 如果试算过也转簿记了，就展示撤销按钮
          // 未试算 已转薄记 就展示试算按钮，
          {
            title: '撤销',
            onClick: (record, index) => {
              this.revocation(record.id);
            },
            isPopWindow: true,
            PopWindowText: '确定撤销',
            rules: {
              hide: {
                items: [{ key: 'isTrial', value: ['Y'], relation: ['='] }],
                relation: 'or',
              },
            },
          },
          {
            title: '转簿记',
            onClick: (record, index) => {
              this.transferBook(record);
            },
            isPopWindow: true,
            PopWindowText: '确定转簿记',
            rules: {
              hide: {
                items: [
                  { key: 'isTrial', value: ['Y'], relation: ['='] },
                  { key: 'isTrialferBook', value: ['Y'], relation: ['='] },
                ],
                relation: 'or',
              },
            },
          },
          {
            title: '试算',
            onClick: (record, index) => {
              this.trialCalculation(record);
            },
            isPopWindow: true,
            PopWindowText: '确定试算',
            rules: {
              hide: {
                items: [{ key: 'isTrial', value: ['Y'], relation: ['!='] }],
                relation: 'or',
              },
            },
          },
        ],
      });
    }
    columns.forEach((element) => {
      if (element.dataIndex === 'createdTs') {
        element.title = '试算时间';
        element.width = 193;
        element.render = (val, record) => {
          return (
            <div>
              <span className={`${style.isTrial} ${record.isTrial == 'Y' ? style.Y : ''}`}></span>
              {moment(val).format('YYYY-MM-DD HH:mm:ss')}
            </div>
          );
        };
      }
      if (element.dataIndex === 'productName') {
        element.title = '产品/组合';
        element.width = 160;
        element.render = (val, record) => (
          <span>
            {record.portfolioCode}-{record.portfolioInfoName}
          </span>
        );
      }
      if (element.dataIndex === 'amount') {
        element.title = '交易价格';
      }
      if (element.dataIndex === 'settlementAmount') {
        element.title = '交易总额';
      }
      if (element.dataIndex === 'orderSide') {
        element.width = 80;
      }
    });
  };

  // 响应撤销
  revocation = (id) => {
    this.props.dispatch({
      type: 'tradeTrialM/revocation',
      payload: { id },
      callback: (res) => {
        if (res) {
          this.getTableData();
        }
      },
    });
  };

  // 非标非理财直融记
  addBookingNon = (record, args) => {
    const params = {
      productCode: record.productCode, // 产品code
      productId: args.productid, // 产品id
      productName: record.productName, // 产品名称
      portfolioCode: record.portfolioCode, // 组合code
      portfolioId: args.portfolioid, // 组合id
      portfolioName: record.portfolioInfoName, // 组合名称
      tradingCode: args.tradingcode, // 证券代码
      tradingName: args.secuabbr, // 证券名称
      exchangeCode: args.exchangeCode, // 交易市场
      tradeDir: args.direction, // 交易方向
      price: args.price, // 价格
      num: args.amount, // 数量
      amount: args.parValueTotal, // 交易总额
      investmentType: args.investmentType, // 投资类型
      remark: args.remark, // 备注
      instructionType: '0', // 0是指簿记
      userDefinedType: args.userDefinedType, // 自定义分类
      businessObjectives: args.bussinessObjectives, // 业务目标
      sppiResult: args.sppiResult, // SPPI结果
      isRelatedInterest: args.isRelatedInterest, // 绩效评估是否与利息收入合同报酬相关数据选择
      isRelatedValue: args.isRelatedValue, // 绩效评估是否与公允价值处分损益相关
      isCurrentYearHandle: args.isCurrentYearHandle, // 最近一年是否有处置
      lastHandleDate: args.lastHandleDate, // 最近一次处置时间
      reason: args.reason, // 处分原因
      interest: args.interest, // 利息
      interestArrivalDate: args.interestArrivalDate, // 利息到账日
    };
    this.setState({
      orderParams: { ...params },
      visibleStep: true,
    });
  };

  // 响应转簿记 验资验券  试算的部分模式下用的新接口也在这验资验券（其中之一）
  transferBook = (record, type) => {
    const { dispatch } = this.props;
    this.setState({
      rowData: record,
    });
    if (Number(record.type) != 6 && type !== 'trial') {
      // 非标  非理财直融
      this.addBookingNon(record, record[`trade${record.type}`]);
      return;
    }
    if (record[`trade${record.type}`]?.direction == '1') {
      dispatch({
        type: 'availableAssetM/queryAvailable',
        payload: { portfolioCode: record.portfolioCode, hkType: '1' },
        callback: (data) => {
          if (data) {
            const keys = keyWordConfig[record.type].settlementAmount;
            if (parseFloat(data?.t1Fund || 0) < parseFloat(record[`trade${record.type}`][keys])) {
              message.error('交易总额不能大于t+0可用!');
              return;
            }
            if (type !== 'trial') {
              // 簿记下达
              this.addBooking(record[`trade${record.type}`], record);
            } else {
              // 试算下达
              this.addTrialCalculation(record[`trade${record.type}`], record.type, record);
            }
          } else {
            message.error('交易总额不能大于t+0可用!');
          }
        },
      });
    } else {
      const args = record[`trade${record.type}`];
      dispatch({
        type: 'tradeHoldM/queryAvailablePosition',
        payload: {
          portfolioCode: record.portfolioCode,
          tradingCode: args.tradingcode,
          exchangeCode: args.exchangeCode,
          securityType: record.type == 6 ? '7' : '12',
          hkType: '1',
        },
        callback: (data) => {
          if (data) {
            const { availableAmount } = data;
            const keys = keyWordConfig[record.type].tAmount;
            if (parseFloat(availableAmount || 0) < parseFloat(record[`trade${record.type}`][keys])) {
              message.error('交易数量不能大于可用数量!');
              return;
            }
            if (type !== 'trial') {
              // 簿记下达
              this.addBooking(record[`trade${record.type}`], record);
            } else {
              // 试算下达
              this.addTrialCalculation(record[`trade${record.type}`], record.type, record);
            }
          } else {
            message.error('交易数量不能大于可用数量!');
          }
        },
      });
    }
  };

  // 下簿记
  addBooking = (data, record) => {
    const { dispatch } = this.props;
    if (record.type == 6) {
      // 理财直融
      dispatch({
        type: 'finaFlockingM/tradeBookSave',
        // tradeInstruction新增  method需要值区分
        payload: { ...data, method: 0, tradeInstruction: { direction: data.direction, stockCode: record.tradingCode } },
        callback: (res) => {
          if (res.success == true) {
            dispatch({
              type: 'tradeTrialM/istrialferbookTrade',
              payload: { id: record.id },
              callback: (res) => {
                message.success('转簿记成功');
                this.getTableData();
              },
            });
          } else {
            message.error(res.message);
          }
        },
      });
    }
  };

  // 响应试算
  trialCalculation = (record) => {
    if (this.props.modes === 'COMMAND_MODE' || this.props.modes === 'BOOKKEEPING_MODE') {
      // 这种模式下 用新的验资验券 接口
      this.transferBook(record, 'trial');
      return;
    }
    const { dispatch } = this.props;
    if (record[`trade${record.type}`]?.direction == '1') {
      dispatch({
        type: 'availableAssetM/getFund',
        payload: { nodeId: record[`trade${record.type}`]?.portfolioid, hkType: '1' },
        callback: (data) => {
          if (data && data.length) {
            const { toneAvailableFund } = data[0];
            const keys = keyWordConfig[record.type].settlementAmount;
            if (parseFloat(toneAvailableFund || 0) < parseFloat(record[`trade${record.type}`][keys])) {
              message.error('交易总额不能大于t+0可用!');
              return;
            }
            this.addTrialCalculation(record[`trade${record.type}`], record.type, record);
          }
        },
      });
    } else {
      dispatch({
        type: 'tradeHoldM/getPosition',
        payload: {
          tradingcode: record[`trade${record.type}`]?.tradingcode,
          exchangecode: record[`trade${record.type}`]?.exchangeCode,
          fundId: record[`trade${record.type}`]?.portfolioid,
          securityType: record.type == 6 ? '7' : '12',
          hkType: '1',
        },
        callback: (data) => {
          if (data) {
            const { availableAmount } = data;
            const keys = keyWordConfig[record.type].tAmount;
            if (parseFloat(availableAmount || 0) < parseFloat(record[`trade${record.type}`][keys])) {
              message.error('交易数量不能大于可用数量!');
              return;
            }
            this.addTrialCalculation(record[`trade${record.type}`], record.type, record);
          }
        },
      });
    }
  };

  // 下试算
  addTrialCalculation = (data, type, record) => {
    const { dispatch } = this.props;
    if (type == 6) {
      dispatch({
        type: 'portfolioTrialAddM/finaFlockingSave',
        payload: { ...data, trialId: record.id, type: 'workstation' },
        callback: (res) => {
          if (res.success == true) {
            message.success('试算成功');
            this.getTableData();
          }
        },
      });
    } else {
      dispatch({
        type: 'portfolioTrialAddM/nonstandardOrderSave',
        payload: { ...data, trialId: record.id, type: 'workstation' },
        callback: (res) => {
          if (res.success == true) {
            message.success('试算成功');
            this.getTableData();
          }
        },
      });
    }
  };

  // 模态框内容
  modalContent = () => {
    const { loading } = this.props;
    const { columns, dataSource, pageInfo } = this.state;
    this.changeColumns(columns);
    return (
      <div>
        <TableC
          columns={columns || []}
          dataSource={dataSource || []}
          scroll={{ x: 1100, y: 320 }}
          loading={loading.effects['portfolioTrialM/getList']}
          rowKey={'id'}
          size={'small'}
          onChange={this.handleTableChange}
          current={pageInfo.currentPage}
          pageSize={pageInfo.pageSize}
          total={pageInfo.total}
        />
      </div>
    );
  };

  // 取消
  onCancel = () => {
    this.props.onCancel();
  };

  // 簿记成功事件
  handleSuccess = () => {
    this.setState({
      orderParams: {},
      visibleStep: false,
    });
    this.props.dispatch({
      type: 'tradeTrialM/istrialferbookTrade',
      payload: { id: this.state.rowData.id },
      callback: () => {
        this.getTableData();
      },
    });
  };

  // 簿记失败的 事件
  handleError = () => {
    this.setState({
      orderParams: {},
      visibleStep: false,
    });
  };

  render() {
    const { visibleStep, orderParams } = this.state;
    return (
      <div className={style.modal}>
        <ModalC title={'试算'} visible={this.props.visible} maskClosable={false} onCancel={this.onCancel} width={1200} height={420} footer={null}>
          <div>{this.modalContent()}</div>
        </ModalC>
        {visibleStep ? (
          <OrderC successMsg='转簿记成功!' visible={visibleStep} handleSuccess={this.handleSuccess} handleError={this.handleError} params={orderParams} tradeType={'nonStandBj'} />
        ) : null}
      </div>
    );
  }
}
export default connect(({ portfolioTrialM, tradeTrialM, tradeHoldM, finaFlockingM, nonstandardOrderM, portfolioTrialAddM, loading }) => ({
  portfolioTrialM,
  tradeTrialM,
  tradeHoldM,
  finaFlockingM,
  nonstandardOrderM,
  portfolioTrialAddM,
  loading,
}))(theTrialC);
